<?php

class UserController extends AtomController {
	public $defaultAction = 'details';
	private $_user = null;

	public function loadUser($id = null) {
		if($this->_user === null) {
			if($id !== null || isset($_GET['id']))
				$this->_user = User::model()->findbyPk($id !== null ? $id : $_GET['id']);
			if($this->_user === null)
				throw new CHttpException(500,'The requested torrent does not exist.');
		}
		return $this->_user;
	}

	public function actionPermissions() {
		$user = $this->loadUser();
		
		$permissions = Permission::model()->findAll();

		if (Yii::app()->request->isPostRequest) {
			if(isset($_POST['UserPermissions']))
			{
				$perms = $used->permissions & 1;
				foreach($_POST['UserPermissions'] as $k => $v) {
					$perms &= ~ (float)(1 << (int)$k);
					$perms |= (float)(1 << (int)$k);
				}

				$user->permissions = $perms;
				if(isset($_POST['submitUserPermissions']))
					if ($user->save()) {
						Yii::app()->user->setFlash('permissionsSaved', 'User permissions has been saved');
						$this->redirect(array('permissions','id'=>$user->id));
					}
					else
						$this->addErrors($user->getErrors());
			}
		}
		$this->render('permissions',array('user'=>$user, 'perms' => $permissions));
	}

	public function actionEdit() {
		$user = $this->loadUser();
		if (Yii::app()->request->isPostRequest) {
			if(isset($_POST['User']))
			{
				$user->attributes=$_POST['User'];
				if(isset($_POST['submitUser']))
					if ($user->save()) {
						Yii::app()->user->setFlash('detailsSaved', 'User details has been saved');
						$this->redirect(array('details','id'=>$user->id));
					}
					else
						$this->addErrors($user->getErrors());
			}
		}
		$this->render('edit',array('user'=>$user));
	}

	public function actionDelete() {
		$this->loadUser()->delete();
		$this->redirect('/admin/users');
	}

	public function actionDetails() {
		$user = $this->loadUser();
		$this->render('details', array('user' => $user));

	}

	public function actionGetUserBag() {
		$user = User::model()->findByPk(Yii::app()->user->id);
		echo ($user != null) ? $user->bag : '';
	}

	public function actionSetUserBag() {
		$arr = $_POST['bag'];
		$user = User::model()->findByPk(Yii::app()->user->id);
		$user->bag = $arr;
		if ($user->save())
			echo 'ok';
	}

}

?>
